package com.magic.zhixin.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

@RestController
@RequestMapping("/log/")
public class LogController {
    private Logger log = LoggerFactory.getLogger(LogController.class);
    private String logfile0 = "/local/logs/zhixin/log/";
//    private String logfile0 = "/Users/sc/Desktop/ldfeng/";
    @RequestMapping("view")
    public void  view(String fileName, Integer pageNo, Integer pageSize, HttpServletResponse resp){
        String logfile= logfile0 +fileName;
        FileReader fileReader = null;
        LineNumberReader lnread = null;
        try {
            StringBuffer sb = new StringBuffer();
            Integer startIndext = null;
//            Integer endIndext = null;
//            Long offset= 0l;
            fileReader = new FileReader(logfile);

            if (pageNo == null || pageSize == null) {
                pageNo = 1;
                pageSize = 10;
            }
            pageNo = pageNo -1;
            startIndext = pageNo * pageSize;
            int endLine = startIndext + pageSize;
            lnread = new LineNumberReader(fileReader);
            lnread.setLineNumber(startIndext);
            String line = null;
            for (int i = 0; i < endLine; i++) {
                    try {
                        if ((line = lnread.readLine()) != null) {
                            if (i < startIndext) {
                                continue;
                            }
                            sb.append(line);
                            sb.append(System.getProperty("line.separator"));
//                            resp.setCharacterEncoding("utf-8");
//                            resp.getWriter().println(line);
                        }
                    } catch (IOException e) {
                        log.error(e.toString());
                    }
                }
                resp.setCharacterEncoding("utf-8");
                resp.getWriter().println(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

                try {
                    fileReader.close();
                    lnread.close();
                } catch (IOException e) {
                    log.error(e.toString());
                }
            }

//            return sb;
    }
}
